<?php
class Story_ChapterController extends Core_Controller_Action_Standard
{
	public function getCategoryTable()
	{
		return Engine_Api::_()->getItemTable('story_category');
	}

	public function getChapterTable(){
		return Engine_Api::_()->getItemTable('story_chapter');
	}

	public function indexAction()
	{
		$story_id = $this->_getParam('story_id', '');
		if(empty($story_id)){
			$this->_forward('notfound');
		}

		$story = Engine_Api::_()->getItem('story', $story_id);
		if(!$story){
			return $this->_forward('notfound');
		}

		$this->checkAllowChapter($story);

		// Get navigation
		$this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')->getNavigation('story_main');
		$this->view->categories = $this->getChapterTable()->getChapters($story_id);
		$this->view->story_id = $story_id;
		$this->view->story = $story;
	}

	public function createAction()
	{
		if (!$this->_helper->requireAuth()->setAuthParams('story', null, 'create')->isValid()){
			return;
		}
		$viewer = Engine_Api::_()->user()->getViewer();

		$story_id = $this->_getParam('story_id');
		if(empty($story_id)){
			return $this->_forward('notfound');
		}

		$story = Engine_Api::_()->getItem('story', $story_id);
		if(!$story){
			return $this->_forward('notfound');
		}

		//Check permission
		if(!$story->isOwner($viewer) && !$viewer->isAdmin()){
			return $this->_forward('requireauth', 'error', 'core');
		}

		$this->checkAllowChapter($story);

		$this->view->form = $form = new Story_Form_Chapter(array('item' => $story));
		if (!$this->getRequest()->isPost()){
			return;
		}

		if (!$form->isValid($this->getRequest()->getPost())){
			return;
		}

		//We will add the category
		$values = $form->getValues();
		$chapterTable = Engine_Api::_()->getDbTable('chapters', 'story');
		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();
		try
		{
			$values['user_id'] = 0;
			$chapter = $chapterTable->createRow();
			$chapter->setFromArray($values);
			$chapter->user_id = $viewer->getIdentity();
			$chapter->story_id = $story_id;
			$chapter->public = 1;
			//Default order = 1
			$chapter->order = $chapterTable->getLastOrder($story_id);
			$chapter->save();
			$db->commit();

			$story->body = $chapter->body;
			$story->save();

			// Add notification
			$notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
			$table = Engine_Api::_()->getDbTable("follow", "story");
      		$user_follow = $table->getUserFollow($story->story_id);
      		foreach($user_follow as $row){
				$following = $viewer;
				$follower = Engine_Api::_()->user()->getUser($row->user_id);
				$notifyApi->addNotification($follower, $following, $story, 'story_follow');
      		}
		}
		catch( Exception $e ){
			$db->rollBack();
			throw $e;
		}

		$this->_forward('success', 'utility', 'core', array(
				'smoothboxClose' => 10,
				'parentRefresh'=> 10,
				'messages' => array(Zend_Registry::get('Zend_Translate')->_('Chapter added.'))
		));

	}

	public function orderAction()
	{
		if (!$this->getRequest()->isPost()) {
			return;
		}

		$story_id = $this->_getParam('story_id');
		if(empty($story_id)){
			return $this->_forward('notfound');
		}

		$story = Engine_Api::_()->getItem('story', $story_id);
		if(!$story){
			return $this->_forward('notfound');
		}

		$this->checkAllowChapter($story);
		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();
		try
		{
			$categories = $this->getChapterTable()->getChapters($story_id);
			foreach ($categories as $category){
				$order = $this->getRequest()->getParam('admin_category_item_'.$category->getIdentity());
				//echo $order;
				$category->order = $order;
				$category->save();
			}

			$db->commit();
		}
		catch( Exception $e){
			$db->rollBack();
			throw $e;
		}

		return;
	}

	public function editAction()
	{
		$chapter_id = $this->_getParam('chapter_id');
		$chapter = Engine_Api::_()->getItem('story_chapter', $chapter_id);
		if(!$chapter){
			return $this->_forward('requireauth', 'error', 'core');
		}

		$story = $chapter->getStory();
		$this->checkAllowChapter($story);
		$this->view->form = $form = new Story_Form_Chapter(array('item' => $story));
				
		if($story->category_id == Story_Model_Category::SCRIPT_PLAY){
			$form->submit->setLabel('Update Scene');
		} else {
			$form->submit->setLabel('Update Chapter');
		}
		$form->populate($chapter->toArray());

		if (!$this->getRequest()->isPost()){
			return;
		}

		if (!$form->isValid($this->getRequest()->getPost())){
			return;
		}

		$values = $form->getValues();
		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();
		try {
			$chapter->setFromArray($values);
			$chapter->save();
			$db->commit();
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}

		$this->_forward('success', 'utility', 'core', array(
				'smoothboxClose' => 10,
				'parentRefresh'=> 10,
				'messages' => array(Zend_Registry::get('Zend_Translate')->_('Chapter updated.'))
		));

	}


	public function deleteAction()
	{

		$chapter_id = $this->_getParam('chapter_id');

		$chapter = Engine_Api::_()->getItem('story_chapter', $chapter_id);
		if(!$chapter){			
			return $this->_forward('requireauth', 'error', 'core');
		}

		$story = $chapter->getStory();
		$this->checkAllowChapter($story);

		$this->view->form = $form = new Story_Form_Delete();


		if (!$this->getRequest()->isPost())
		{
			return;
		}

		if (!$form->isValid($this->getRequest()->getPost())){
			return;
		}

		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();

		try
		{
			$chapter->delete();
			$db->commit();			
		}

		catch( Exception $e )
		{
			$db->rollBack();
			throw $e;
		}

		$this->_forward('success', 'utility', 'core', array(
				'smoothboxClose' => 10,
				'parentRefresh'=> 10,
				'messages' => array(Zend_Registry::get('Zend_Translate')->_('Chapter deleted.'))
		));

	}

	private function checkAllowChapter($story){
		if($story && $story->allowChapters() == false){
			return $this->_forward('requireauth', 'error', 'core');
		}
	}
}